package api

import (
	"company_website/src/global"
	"company_website/src/model"
	"company_website/src/model/common"
	"company_website/src/model/request"
	"company_website/src/model/response"
	"company_website/src/server"
	"github.com/gin-gonic/gin"
)

type Admin struct {
}

// AdminList 分页获取成员列表
func (a Admin) AdminList(c *gin.Context) {
	reqInfo := &common.GetPageInfo{}
	if err := c.ShouldBindJSON(&reqInfo); err != nil {
		global.GVL_LOG.Error("接受参数失败", err)
		response.FailWithMessage("接受参数失败", c)
		return
	}
	//到数据库中查找数据
	resInfo, err := server.AdminServer.GetAllAdminInfoPage(reqInfo)
	if err != nil {
		global.GVL_LOG.Error("获取成员列表失败", err)
		response.FailWithMessage("获取成员列表失败", c)
		return
	}
	response.OkWithData(resInfo, c)
}

// AdminSearch 搜索成员
func (a Admin) AdminSearch(c *gin.Context) {
	var adminRequest request.Search
	err := c.ShouldBindJSON(&adminRequest)
	if err != nil {
		response.FailWithMessage("绑定失败", c)
		return
	}
	var admins []*model.AdminUser
	tx := GetAdminList()
	err = tx.Where("admin_name like ?", "%"+adminRequest.AdminName+"%").Find(&admins).Error
	if err != nil {
		response.FailWithMessage("查询失败", c)
		return
	}
	var list []*response.List
	for _, v := range admins {
		data := &response.List{
			AdminName:     v.AdminName,
			Sex:           v.Sex,
			Authorization: v.Authorizations,
		}
		list = append(list, data)
	}
	response.OkWithData(list, c)
}

// SetAdminAuthorization 设置成员管理权限
func (a Admin) SetAdminAuthorization(c *gin.Context) {
	var adminAuth request.Authorization
	err := c.ShouldBindJSON(&adminAuth)
	if err != nil {
		response.FailWithMessage("绑定失败", c)
		return
	}
	var admin model.AdminUser
	db := global.GVL_DB.Model(&model.AdminUser{}).Preload("Authorizations")
	err = db.Model(&model.AdminUser{}).Where("id = ?", adminAuth.AdminId).Find(&admin).Error
	if err != nil {
		response.FailWithMessage("查询成员信息失败", c)
	}
	err = global.GVL_DB.Model(&model.Authorization{}).Where("admin_id = ? and model_name = ?", adminAuth.AdminId, adminAuth.ModelName).Update("status", adminAuth.Status).Error
	if err != nil {
		response.FailWithMessage("设置成员管理权限失败", c)
	}
	data := response.List{
		AdminName:     admin.AdminName,
		Sex:           admin.Sex,
		Authorization: admin.Authorizations,
	}
	response.OkWithData(data, c)
}
